<template>
  <div
    class="ai-assistant-float"
    :class="{ 'ai-assistant-expanded': isExpanded }"
    :style="{ left: position.x + 'px', top: position.y + 'px' }"
    @mousedown="startDrag"
    @touchstart="startDrag"
  >
    <!-- AI助手图标 -->
    <div class="ai-assistant-icon" @click="toggleAssistant">
      <i class="iconfont icon-a-aizhushou_huaban1fuben15_huaban1fuben15"></i>
    </div>

    <!-- AI助手对话框 -->
    <div class="ai-assistant-dialog" v-if="isExpanded">
      <div class="ai-dialog-header">
        <h3><i class="el-icon-aim"></i> AI助手</h3>
        <el-button type="text" @click="closeAssistant" class="close-btn">
          <i class="el-icon-close"></i>
        </el-button>
      </div>

      <div class="ai-dialog-content">
        <div class="ai-messages" ref="aiMessagesContainer">
          <div
            v-for="(msg, index) in aiMessages"
            :key="index"
            :class="['ai-message', msg.type, { 'loading': msg.loading }]"
          >
            <div class="message-content" v-if="!msg.loading">{{ msg.content }}</div>
            <div class="loading-dots" v-else>
              <div class="dot"></div>
              <div class="dot"></div>
              <div class="dot"></div>
            </div>
            <div class="message-time" v-if="!msg.loading">{{ msg.time }}</div>
          </div>
        </div>

        <div class="ai-input">
          <el-input
            v-model="aiInput"
            placeholder="请输入您的问题..."
            @keyup.enter="sendAIQuestion"
            :disabled="aiLoading"
            clearable
          >
            <template #append>
              <el-button
                type="primary"
                @click="sendAIQuestion"
                :loading="aiLoading"
                :disabled="!aiInput.trim()"
              >
                <i class="el-icon-position" v-if="!aiLoading"></i>
                发送
              </el-button>
            </template>
          </el-input>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useUserStore } from '@/stores/user'
import { chatWithAI, getSystemStatus } from '@/api/ai'
import { ElMessage } from 'element-plus'

// 用户状态管理
const userStore = useUserStore()

// 响应式数据定义
const isExpanded = ref(false)
const aiMessages = ref([
  { type: 'ai', content: '您好！我是您的AI助手，有什么我可以帮助您的吗？', time: new Date().toLocaleTimeString() }
])
const aiInput = ref('')
const aiLoading = ref(false)
const aiMessagesContainer = ref(null)

// 位置状态
const position = ref({
  x: window.innerWidth - 100,
  y: window.innerHeight - 100
})

// 拖拽相关状态
const isDragging = ref(false)
const dragOffset = ref({ x: 0, y: 0 })

// 系统状态数据
const systemStatus = ref({
  unreadMessagesCount: 0,
  globalUnreadMessagesCount: 0,
  userUnreadMessagesCount: 0,
  pendingFilesCount: 0,
  activeWorkflowsCount: 0
})

// 方法：开始拖拽
const startDrag = (event) => {
  isDragging.value = true

  // 获取鼠标/触摸位置
  const clientX = event.clientX || (event.touches && event.touches[0].clientX)
  const clientY = event.clientY || (event.touches && event.touches[0].clientY)

  // 计算偏移量
  dragOffset.value = {
    x: clientX - position.value.x,
    y: clientY - position.value.y
  }

  // 添加事件监听器
  document.addEventListener('mousemove', handleDrag)
  document.addEventListener('touchmove', handleDrag, { passive: false })
  document.addEventListener('mouseup', stopDrag)
  document.addEventListener('touchend', stopDrag)

  // 防止文本选择
  event.preventDefault()
}

// 方法：处理拖拽
const handleDrag = (event) => {
  if (!isDragging.value) return

  // 获取鼠标/触摸位置
  const clientX = event.clientX || (event.touches && event.touches[0].clientX)
  const clientY = event.clientY || (event.touches && event.touches[0].clientY)

  // 更新位置
  position.value = {
    x: clientX - dragOffset.value.x,
    y: clientY - dragOffset.value.y
  }

  // 防止页面滚动
  event.preventDefault()
}

// 方法：停止拖拽
const stopDrag = () => {
  isDragging.value = false

  // 移除事件监听器
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('touchmove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
  document.removeEventListener('touchend', stopDrag)
}

// 方法：切换助手显示状态
const toggleAssistant = () => {
  // 如果正在拖拽，不触发点击事件
  if (isDragging.value) return

  isExpanded.value = !isExpanded.value
  if (isExpanded.value) {
    // 获取系统状态
    fetchSystemStatus()
    // 滚动到底部
    scrollToBottom()
  }
}

// 方法：关闭助手
const closeAssistant = () => {
  isExpanded.value = false
}

// 方法：发送AI问题
const sendAIQuestion = async () => {
  if (!aiInput.value.trim() || aiLoading.value) return

  // 添加用户消息
  aiMessages.value.push({
    type: 'user',
    content: aiInput.value,
    time: new Date().toLocaleTimeString()
  })

  // 清空输入框
  const question = aiInput.value
  aiInput.value = ''
  aiLoading.value = true

  // 滚动到底部
  scrollToBottom()

  // 添加AI加载消息
  aiMessages.value.push({
    type: 'ai',
    loading: true,
    content: '',
    time: ''
  })

  try {
    // 调用AI接口，传递系统上下文信息
    const response = await chatWithAI({
      message: question,
      context: systemStatus.value,
      user: {
        role: userStore.user?.role || userStore.role || 'user'
      }
    })

    // 移除加载消息
    aiMessages.value.pop()

    if (response.code === 200) {
      // 添加AI回复
      aiMessages.value.push({
        type: 'ai',
        content: response.data.reply,
        time: new Date().toLocaleTimeString()
      })
    } else {
      ElMessage.error(response.message || 'AI助手回复失败')
      // 添加错误回复
      aiMessages.value.push({
        type: 'ai',
        content: response.message || '抱歉，AI助手回复失败，请稍后再试。',
        time: new Date().toLocaleTimeString()
      })
    }
  } catch (error) {
    console.error('AI助手调用失败:', error)
    ElMessage.error('AI助手调用失败')

    // 移除加载消息
    aiMessages.value.pop()

    // 添加错误回复
    aiMessages.value.push({
      type: 'ai',
      content: '抱歉，我暂时无法回答您的问题，请稍后再试。',
      time: new Date().toLocaleTimeString()
    })
  } finally {
    aiLoading.value = false
    // 滚动到底部
    scrollToBottom()
  }
}

// 方法：滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (aiMessagesContainer.value) {
    aiMessagesContainer.value.scrollTop = aiMessagesContainer.value.scrollHeight
  }
}

// 获取系统状态
const fetchSystemStatus = async () => {
  try {
    const response = await getSystemStatus()
    if (response.code === 200) {
      systemStatus.value = response.data

      // 检查未读消息并提醒
      if (response.data.unreadMessagesCount > 0) {
        // 添加AI提醒消息
        aiMessages.value.push({
          type: 'ai',
          content: `重要提醒：检测到您有 ${response.data.unreadMessagesCount} 条未读消息`,
          time: new Date().toLocaleTimeString()
        })
      }
    }
  } catch (error) {
    console.error('获取系统状态失败:', error)
  }
}

// 组件挂载时的处理
onMounted(() => {
  // 设置初始位置
  position.value = {
    x: window.innerWidth - 100,
    y: window.innerHeight - 100
  }
})
</script>

<style lang="scss" scoped>
.ai-assistant-float {
  position: fixed;
  z-index: 9999;
  user-select: none;

  // AI助手图标
  .ai-assistant-icon {
    width: 60px;
    height: 60px;
    background: linear-gradient(135deg, #409eff, #337ecc);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
    transition: all 0.3s ease;

    &:hover {
      transform: scale(1.1);
      box-shadow: 0 6px 16px rgba(64, 158, 255, 0.6);
    }

    .iconfont {
      font-size: 24px;
      color: white;
    }
  }

  // AI助手对话框
  .ai-assistant-dialog {
    position: absolute;
    bottom: 70px;
    right: 0;
    width: 350px;
    height: 500px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .ai-dialog-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 20px;
      background: linear-gradient(135deg, #409eff, #337ecc);
      color: white;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;

        i {
          margin-right: 8px;
        }
      }

      .close-btn {
        color: white;
        font-size: 18px;

        &:hover {
          color: #f5f5f5;
        }
      }
    }

    .ai-dialog-content {
      flex: 1;
      display: flex;
      flex-direction: column;

      .ai-messages {
        flex: 1;
        overflow-y: auto;
        padding: 15px;
        background: #f5f7fa;

        .ai-message {
          margin-bottom: 15px;
          padding: 12px 15px;
          border-radius: 18px;
          animation: messageFadeIn 0.3s ease-out;

          &.user {
            background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
            color: white;
            text-align: right;
            margin-left: 20%;
            border-bottom-right-radius: 4px;
            box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);

            .message-content {
              font-weight: 500;
            }
          }

          &.ai {
            background: white;
            text-align: left;
            margin-right: 20%;
            border-bottom-left-radius: 4px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            border: 1px solid #ebeef5;
          }

          .message-content {
            margin: 0;
            padding: 0;
            background: transparent;
            white-space: pre-wrap;
            word-wrap: break-word;
            line-height: 1.5;
            font-size: 14px;
          }

          .message-time {
            font-size: 12px;
            color: #909399;
            margin-top: 8px;
            text-align: right;
          }

          // 加载动画
          &.ai.loading {
            display: flex;
            align-items: center;
            justify-content: center;
            background: white;
            border: 1px solid #ebeef5;

            .loading-dots {
              display: flex;

              .dot {
                width: 8px;
                height: 8px;
                background-color: #409eff;
                border-radius: 50%;
                margin: 0 3px;
                animation: bounce 1.5s infinite;

                &:nth-child(2) {
                  animation-delay: 0.2s;
                }

                &:nth-child(3) {
                  animation-delay: 0.4s;
                }
              }
            }
          }
        }
      }

      .ai-input {
        padding: 15px;
        border-top: 1px solid #ebeef5;

        :deep(.el-input__wrapper) {
          border-radius: 24px;

          &:hover {
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
          }

          &:focus {
            box-shadow: 0 2px 16px rgba(64, 158, 255, 0.3);
          }
        }

        :deep(.el-input-group__append) {
          background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
          border-color: #409eff;
          border-radius: 24px;
          padding: 0 20px;

          .el-button {
            color: white;
            font-weight: 500;

            &:hover {
              background: linear-gradient(135deg, #337ecc 0%, #2a6bb3 100%);
            }
          }
        }
      }
    }
  }
}

// 动画效果
@keyframes messageFadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes bounce {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-5px);
  }
}
</style>
